<!--  -->
<template>
  <div class='authority'>
    <el-button type="primary" v-permissions="'pen:add'" @click="addPenInPage" style="margin-bottom: 10px;">新增</el-button>
    <!-- 查询 -->
    <el-form :inline="true" :model="addFromFroPen" class="demo-form-inline">
      <el-form-item label="圈棚名称">
        <el-input v-model="addFromFroPen.kw" placeholder="请输入牧场名称"></el-input>
      </el-form-item>
      <el-form-item label="所属牧场">
        <el-select v-model="addFromFroPen.ranchId" placeholder="请选择">
          <el-option
          v-for="(item,index) in addFromFroPen.penRanch"
          :key="index"
          :label="item.name"
          :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitSrearch">查询</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
    <div>
      <!-- 列表展示 -->
      <el-table
        :data="getMyRanch"
        style="width: 100%">
        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column
          type="index"
          label="序号"
          width="55">
        </el-table-column>
        <el-table-column
          prop="penName"
          label="圈棚名称"
          width="80">
        </el-table-column>
        <el-table-column
          prop="penRemark"
          label="备注"
          width="80">
        </el-table-column>
        <el-table-column
          prop="ranchName"
          label="所属牧场"
          width="80">
        </el-table-column>
        <el-table-column
          prop="penAddress"
          label="具体位置"
          width="160">
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          >
          <template slot-scope="scope">
            <el-button v-permissions="'pen:detail'" @click="getRoleDetail(scope.row.id)" type="text" size="small">详情</el-button>
            <!-- <el-button @click="setRoleDetail(scope.row.id,scope.row.roleName)" type="text" size="small">修改</el-button> -->
            <el-button v-permissions="'pen:delete'" @click="deletRoleUser(scope.row.id)" type="text" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div>
      <el-dialog
        title="圈棚详情"
        :visible.sync="dialogVisible"
        :close-on-click-modal="false"
        :show-close="false"
        :close-on-press-escape="true"
        width="50%">
        <el-form
          ref="penUpdateDetail"
          :rules="updatePenForRule"
          :model="updatedPenDetail"
          :disabled="isDisabled"
          :inline="false"
          class="demo-form-inline"
          label-position="left"
          label-width="auto">
          <div class="filter-container">
            <el-form-item label="圈棚名称" prop="penName">
              <el-input v-model="updatedPenDetail.penName"></el-input>
            </el-form-item>
            <el-form-item label="地址" prop="detailsAddress">
              <el-cascader
                class="widthSmall"
                size="large"
                :options="options"
                v-model="updatedPenDetail.detailsAddress"
                @change="ChangeDetailsAddress">
              </el-cascader>
            </el-form-item>
            <el-form-item label="详细地址" prop="addressPlot">
              <el-input v-model="updatedPenDetail.addressPlot" @input='myInputNotUpdate'></el-input>
            </el-form-item>
            <el-form-item label="备注">
              <el-input type="textarea" v-model="updatedPenDetail.penRemark"></el-input>
            </el-form-item>
            <el-form-item label="所属牧场" prop="ranchId">
              <el-select v-model="updatedPenDetail.ranchId" placeholder="请选择">
                <el-option
                v-for="(item,index) in addFromFroPen.penRanch"
                :key="index"
                :label="item.name"
                :value="item.id"></el-option>
              </el-select>
            </el-form-item>

          </div>
        </el-form>
        <div class="buttons">
           <el-button type="primary" v-permissions="'pen:update'" @click="setConfigUserRole" v-if="isDisabled">修改</el-button>
           <el-button type="primary" @click="submitConfigUser" v-if="!isDisabled">保存</el-button>
           <el-button @click="closeDiaDetail">关闭</el-button>
        </div>
      </el-dialog>

      <el-dialog
        title="新增圈棚"
        :visible.sync="addCompany"
        @close="closeDia"
        :close-on-press-escape="true"
        :close-on-click-modal="false"
        width="50%">
        <el-form ref="formName" :model="formAddpen" :rules="addUserRule" label-width="80px">
          <el-form-item label="棚圈名称" prop="name">
            <el-input v-model="formAddpen.name"></el-input>
          </el-form-item>
          <el-form-item label="地址" prop="selectedOptions">
            <el-cascader
              class="widthSmall"
              size="large"
              :options="options"
              v-model="formAddpen.selectedOptions"
              @change="addressChange">
            </el-cascader>
          </el-form-item>
          <el-form-item label="详细地址" prop="address">
            <el-input type="textarea" v-model="formAddpen.address"></el-input>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="formAddpen.remark"></el-input>
          </el-form-item>
          <el-form-item label="所属牧场" prop="ranchId">
            <el-select v-model="formAddpen.ranchId" placeholder="请选择">
              <el-option
              v-for="(item,index) in formAddpen.ranchListInpen"
              :key="index"
              :label="item.name"
              :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div style="width: 100%; text-align: center;">
          <el-button type="primary" @click="addMyNewCompany">保存</el-button>
        </div>
      </el-dialog>
    </div>
    <pagination
      class="pagination_container"
      :total="pagination.total"
      :page-sizes="[10, 20, 50, 100]"
      :page.sync="pagination.page"
      :limit.sync="pagination.pageSize"
      @pagination="getPenListInit"
    />
  </div>
</template>

<script>
import { provinceAndCityData, CodeToText } from 'element-china-area-data'
import { penList, penAdd, penDetail, penUpdate } from '@/api/pen'
import { ranchRanchList } from '@/api/ranch'
import Pagination from '@/components/pagination'
export default {
  // import引入的组件需要注入到对象中才能使用
  components: {
    Pagination
  },
  data () {
    // 这里存放数据
    return {
      options: provinceAndCityData, // 省市区数据
      isDisabled: true,
      updatedPenDetail: { // 修改圈棚
        address: '',
        cityCode: '',
        penName: '',
        penId: '',
        ranchId: '',
        penRemark: '',
        ranchName: '',
        detailsAddress: [],
        wordForDetailAddress: '',
        addressPlot: ''
      },
      updatePenForRule: {
        penName: [
          { required: true, trigger: 'blur', message: '请输入您的名字' }
        ],
        detailsAddress: [
          { required: true, trigger: 'change', message: '请选择' }
        ],
        ranchId: [
          { required: true, trigger: 'change', message: '请选择牧场' }
        ],
        addressPlot: [
          { required: true, trigger: 'blur', message: '请输入您的详细地址' }
        ]
      },
      getMyRanch: [], // 列表
      formAddpen: { // 新增圈棚
        name: '',
        selectedOptions: [],
        address: '',
        ranchListInpen: [],
        cityProvince: '',
        cityCode: '',
        ranchId: '',
        remark: ''
      },
      // 新增 rule 验证
      addUserRule: {
        name: [
          { required: true, trigger: 'blur', message: '请输入您的名字' }
        ],
        selectedOptions: [
          { required: true, trigger: 'change', message: '请选择' }
        ],
        ranchId: [
          { required: true, trigger: 'change', message: '请选择牧场' }
        ],
        address: [
          { required: true, trigger: 'blur', message: '请输入您的详细地址' }
        ]
      },
      // 分页
      pagination: {
        page: 1,
        pageSize: 10,
        total: 0
      },
      // 查询
      addFromFroPen: {
        penName: '',
        ranchId: '',
        penRanch: []
      },
      // checked: false,
      dialogVisible: false,
      userRemarkGet: '',
      userList: JSON.parse(sessionStorage.getItem('routerList')),
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      defaultCheckRole: [],
      setRoleIdArrFir: [],
      setRoleIdArrSen: [],
      addCompany: false
    }
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  // 方法集合
  methods: {
    // 修改详情地址的时候不更新
    myInputNotUpdate () {
      this.$forceUpdate()
    },
    // 获取牧场列表下拉选
    getRanchListSelect () {
      ranchRanchList().then(res => {
        this.addFromFroPen.penRanch = res.data
        this.formAddpen.ranchListInpen = res.data
      })
    },
    // 修改详情地址
    ChangeDetailsAddress (arr) {
      this.updatedPenDetail.detailsAddress = [arr[0], arr[1]]
      this.updatedPenDetail.wordForDetailAddress = CodeToText[arr[0]] + CodeToText[arr[1]]
    },
    // 地址选择
    addressChange (arr) {
      this.formAddpen.cityCode = arr[0] + '-' + arr[1]
      this.formAddpen.cityProvince = CodeToText[arr[0]] + CodeToText[arr[1]]
      console.log(this.cityCode, CodeToText[arr[0]], CodeToText[arr[1]], 310)
    },
    // 获取圈棚列表
    getPenListInit () {
      penList({
        kw: this.addFromFroPen.kw,
        ranchId: this.addFromFroPen.ranchId,
        limit: this.pagination.pageSize,
        page: this.pagination.page
      }).then(res => {
        if (res.code === '200') {
          this.getMyRanch = res.data.records
          if (res.data.total > 0 && Math.ceil(res.data.total / this.pagination.size) < this.pagination.page) {
            this.pagination.page = Math.ceil(res.data.total / this.pagination.size)
            this.getPenListInit()
          } else {
            this.pagination.total = res.data.total
          }
        } else {
          this.$message({
            message: res.message,
            type: 'warning'
          })
        }
      })
    },
    // 打开新增弹框
    addPenInPage () {
      this.getRanchListSelect()
      this.addCompany = true
    },
    // 新增保存
    addMyNewCompany () {
      this.$refs.formName.validate((valid) => {
        if (valid) {
          this.formAddpen.expireTime = new Date(this.formAddpen.expireTime).getTime()
          const penObj = {
            address: this.formAddpen.cityProvince + '-' + this.formAddpen.address,
            cityCode: this.formAddpen.cityCode,
            name: this.formAddpen.name,
            remark: this.formAddpen.remark,
            ranchId: this.formAddpen.ranchId
          }
          console.log(this.formAddpen, penObj)
          penAdd(penObj).then(res => {
            this.addCompany = false
            if (res.code === '200') {
              this.getPenListInit()
              this.$message({
                message: '操作成功',
                type: 'success'
              })
            } else {
              this.$message({
                message: res.message,
                type: 'error'
              })
            }
          })
        } else {
          return false
        }
      })
    },
    // 查询
    submitSrearch () {
      this.getPenListInit()
    },
    // 重置
    resetForm () {
      this.addFromFroPen.kw = ''
      this.addFromFroPen.ranchId = ''
    },
    // 删除用户
    deletRoleUser (val) {
      // this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
      //     confirmButtonText: '确定',
      //     cancelButtonText: '取消',
      //     type: 'warning',
      //     center: true
      //   }).then(() => {
      //     companyDelete(val).then(res => {
      //       if (res.code === '200') {
      //         this.$message({
      //           message: '删除成功',
      //           type: 'success'
      //         })
      //         this.getPenListInit()
      //       } else {
      //         this.$message({
      //           type: 'info',
      //           message: res,message
      //         });
      //       }
      //     })
      //   }).catch(() => {
      //     this.$message({
      //       type: 'info',
      //       message: '已取消删除'
      //     });
      //   });
    },
    // 用户详情
    getRoleDetail (val) {
      this.dialogVisible = true
      penDetail(val).then(res => {
        this.updatedPenDetail = res.data
        this.updatedPenDetail.penId = res.data.id
        const start = this.updatedPenDetail.penAddress.indexOf('-') + 1
        const detailEnd = this.updatedPenDetail.penAddress.length
        const cityEnd = this.updatedPenDetail.penCityCode.length
        const tagNum = this.updatedPenDetail.penCityCode.indexOf('-')
        const provinceCode = this.updatedPenDetail.penCityCode.substring(0, tagNum)
        const cityForCode = this.updatedPenDetail.penCityCode.substring(tagNum + 1, cityEnd)
        this.updatedPenDetail.detailsAddress = [provinceCode, cityForCode]
        this.updatedPenDetail.wordForDetailAddress = CodeToText[provinceCode] + CodeToText[cityForCode]
        this.updatedPenDetail.addressPlot = this.updatedPenDetail.penAddress.substring(start, detailEnd)
      })
    },
    // 修改用户详情
    setConfigUserRole () {
      console.log(this.updatedPenDetail)
      this.$confirm('是否确认修改圈棚信息', '提示', {
        confirmButtonText: '确定',
        showCancelButton: '取消',
        distinguishCancelAndClose: false
      }).then(() => {
        this.isDisabled = false
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消!'
        })
      })
    },
    // 保存修改后用户信息
    submitConfigUser () {
      this.$refs.penUpdateDetail.validate((valid) => {
        if (valid) {
          const resAddress = this.updatedPenDetail.addressPlot === undefined ? '' : this.updatedPenDetail.addressPlot
          const penConfig = {
            address: this.updatedPenDetail.wordForDetailAddress + '-' + resAddress,
            cityCode: this.updatedPenDetail.detailsAddress[0] + '-' + this.updatedPenDetail.detailsAddress[1],
            name: this.updatedPenDetail.penName,
            penId: this.updatedPenDetail.penId,
            ranchId: this.updatedPenDetail.ranchId,
            remark: this.updatedPenDetail.penRemark
          }
          console.log(penConfig)
          penUpdate(penConfig).then(res => {
            if (res.code === '200') {
              this.$message({
                message: '操作成功',
                type: 'success'
              })
              this.dialogVisible = false
              this.isDisabled = true
              this.getPenListInit()
            } else {
              this.$message({
                type: 'info',
                message: res.message
              })
            }
          })
        }
      })
    },
    // 关闭新增弹框
    closeDia () {
      this.formAddpen = {}
    },
    // 关闭详情弹框
    closeDiaDetail () {
      this.dialogVisible = false
      this.isDisabled = true
    }
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted () {
    this.getPenListInit()
    this.getRanchListSelect()
  }
}
</script>
<style lang='scss' scoped>
  //@import url(); 引入公共css类
.authority {
  width: 100%;
  height: 100%;
}
.fir {
  width: auto;
  height: 30px;
  line-height: 30px;
  span {
    margin-left: 10px;
    padding: 5px;
    width: 30%;
  }
}
.sen {
  margin: 5px auto;
  width: 80%;
  padding: 10px;
  border: 1px solid #f0f0f0;
}
.buttons {
  width: 100%;
  text-align: center;
}
</style>
